<?php
/**
 * Created by PhpStorm.
 * User: C。
 * Date: 2019/8/13
 * Time: 9:04
 */
namespace app\home\controller;

use app\common\model\CompanyGongdengOrder as CompanyGongdengOrderModel;
use app\common\model\Company as CompanyModel;
use app\common\model\Recharge as RechargeModel;
use app\common\model\Config as ConfigModel;
use app\common\model\Practice as PracticeModel;

/**
 * 寺院供灯控制器
 * Class Company
 * @package app\home\controller
 */
class Companygongdengorder extends Base
{
    /**
     * [index  明细列表]
     * @param type 1供灯 2行善 3祈福香 4日行一善
     * @return json
     * @author [C。]
     */
    public function index()
    {
        $param = input('param.');
        $model = new CompanyGongdengOrderModel;
        $this->getPageAndSize($param);
        $map = [];
        $user = $this->user;
        try{
            if(empty($param['home'])){
                $map['c.mid'] = $user['id'];
            }

            if(isset($param['states'])){
                $map['c.states'] = $param['states'];
            }
            $map['c.type'] = $param['type'];
            $map['c.comid'] = $param['comid'];
            $map['c.status'] = 1;
            $field = 'c.id,m.username,m.img,m.tel,c.gongdeng,c.day,c.name,c.to_name,c.content,c.bless,c.bless_img,c.bless_time,c.states,c.total_price,c.paytime,c.foxiang,c.gonghua,c.gongguo';
            $count = $model->getCount($map);//满足条件的总数
            $allpage = intval(ceil($count / $this->size));//总页数
            $lists = $model->getList($map, $this->from, $this->size,$field);
            foreach($lists as &$v){
                $http = substr($v['img'],0,4);
                if($http != 'http'){
                    $v['img'] = config('domain_name').$v['img'];
                }
                $v['residue'] = $v['paytime'] + $v['day']*24*3600 - time();
                $v['residue'] = time2string($v['residue']);
                if($v['residue'] < 0){
                    $v['residue'] = 0;
                }
                $v['paytime'] = date('Y-m-d',$v['paytime']);
                $v['bless_time'] = date('Y-m-d',$v['bless_time']);
            }
        }catch (\Exception $e){
            systembug($e->getMessage(),2,$this->url);
            return admin_json(-1, '获取失败' . $e->getMessage());
        }
        return admin_json(1, '获取成功', [
            'count' => $count,//总记录数
            'allpage' => $allpage,  //总页数
            'lists' => $lists,  //列表数据
        ]);
    }
    /**
     * [can_pay  查询是否可以支付]
     * @param
     * @author [C。]
     * @return json
     */
    public function can_pay()
    {
        $param = input('param.');
        $cmodel = new CompanyModel;
        try{
            $company = $cmodel->findData($param['id'],'id','mch_id,much_secret,wx_appid,wx_secret,is_son');
            if($company['is_son'] == 1){
                if(empty($company['mch_id']) || empty($company['wx_appid'])){
                    return admin_json(2, '暂未开通');
                }
            }else{
                if(empty($company['wx_appid']) || empty($company['wx_secret']) || empty($company['mch_id']) || empty($company['much_secret'])){
                    return admin_json(2, '暂未开通');
                }
            }
        }catch (\Exception $e) {
            systembug($e->getMessage(),2,$this->url);
            return admin_json(-1, '获取失败' . $e->getMessage());
        }
        return admin_json(1, '已开通');
    }
    /**
     * [create_order  创建订单]
     * @param
     * @author [C。]
     * @return json
     */
    public function create_order()
    {
        $param = input('param.');
        $model = new CompanyGongdengOrderModel;
        $cmodel = new CompanyModel;
        $mem = $this->user;
        try{
            $company = $cmodel->findData($param['comid'],'id','mch_id,much_secret,wx_appid,wx_secret,is_son');
            if($company['is_son'] == 1){
                if(empty($company['mch_id']) || empty($company['wx_appid'])){
                    return admin_json(2, '暂未开通');
                }
            }else{
                if(empty($company['wx_appid']) || empty($company['wx_secret']) || empty($company['mch_id']) || empty($company['much_secret'])){
                    return admin_json(2, '暂未开通');
                }
            }
            $param['order_num'] = date('Ymd') . time().str_pad(mt_rand(1, 99999), 5, '0');
            $param['mid'] = $mem['id'];
            $id = $model->addData($param);
        }catch (\Exception $e){
            systembug($e->getMessage(),2,$this->url);
            return admin_json(-1, '创建失败' . $e->getMessage());
        }
        return admin_json(1, '创建成功',$id);
    }
    /**
     * [huixiang  回向]
     * @param
     * @author [C。]
     * @return json
     */
    public function huixiang()
    {
        $param = input('param.');
        $model = new CompanyGongdengOrderModel;
        $pmodel = new PracticeModel;
        try{
            $model->editData(['id'=>$param['id'],'to_name'=>$param['to_name'],'content'=>$param['content']]);
            $practice = $pmodel->getRound(['type'=>3],'content');
        }catch (\Exception $e){
            systembug($e->getMessage(),2,$this->url);
            return admin_json(-1, '失败' . $e->getMessage());
        }
        return admin_json(1, '成功',['content'=>$practice['content'],'order_id'=>$param['id']]);
    }
    /**
     * [pay_success  支付成功]
     * @param
     * @author [C。]
     * @return json
     */
    public function pay_success()
    {
        $param = input('param.');
        $model = new CompanyGongdengOrderModel;
        try{
            $data = $model->findData($param['id'],'id','create_time');
            $time = time() - strtotime($data['create_time']);
            if($time > 60*60){
                return admin_json(-1, '超时！');
            }
            $model->editData(['id'=>$param['id'],'status'=>1,'paytime'=>time()]);
        }catch (\Exception $e){
            systembug($e->getMessage(),2,$this->url);
            return admin_json(-1, '修改失败' . $e->getMessage());
        }
        return admin_json(1, '修改成功');
    }
    /**
     * [pay  微信支付]
     * @param
     * @author [C。]
     * @return json
     */
    public function pay()
    {
        $param = input('param.');
        $model = new CompanyModel;
        $rmodel = new RechargeModel;
        $cmodel = new CompanyGongdengOrderModel;
        if($param['is_act'] == 1){
            $order = $rmodel->findData($param['orderid'],'id','comid,myorderno,title,amt');
            $order['order_num'] = $order['myorderno'];
            $order['gongdeng'] = $order['title'];
            $order['total_price'] = $order['amt'];
        }else{
            $order = $cmodel->findData($param['orderid'],'id','comid,order_num,gongdeng,total_price');
        }
        $data = $model->findData($order['comid'],'id','mch_id,much_secret,wx_appid,wx_secret,is_son');
        if(!empty($param['price'])){
            $price = $param['price']*100;
            $order['order_num'] = date('Ymd') . time().str_pad(mt_rand(1, 99999), 5, '0');
        }else{
            $price = $order['total_price']*100;
        }
        if($data['is_son'] == 1){
            $cmmodel = new ConfigModel;
            $appid = $cmmodel->findOne(['cname'=>'zh_appid'],'cvalue');
//            $secret = $cmmodel->findOne(['cname'=>'zh_secret'],'cvalue');
            $mch_id = $cmmodel->findOne(['cname'=>'zh_mch_id'],'cvalue');
            $mch_secret = $cmmodel->findOne(['cname'=>'zh_mch_secret'],'cvalue');
            $weixinpay = new \WeixinPay\WeixinServerPay($appid['cvalue'],$data['wx_appid'],$param['openid'],$mch_id['cvalue'],$data['mch_id'],$mch_secret['cvalue'],$order['order_num'],$order['gongdeng'],$price);
            //$weixinpay = new \WeixinPay\WeixinServerPay('wxaa0a605773a1ffb9','wxa4c689ed8ebfd6b1','ojnuYxC5WsMCVJX932L_XxhZRtcE','1576331821','1580096641','423a513c80a2d44e1ac825101218aec6','234','123','1');
            //$weixinpay = new \WeixinPay\WeixinServerPay('wx7ec2e73138d0d29a','wxaa0a605773a1ffb9',$param['openid'],'1569584801','1575296371','97cbf945fc5548a5087f8bf7a4ed9800',$order['order_num'],$order['gongdeng'],$price);
        }elseif($data['is_son'] == 2){
            $weixinpay = new \WeixinPay\WeixinPay($data['wx_appid'],$param['openid'],$data['mch_id'],$data['much_secret'],$order['order_num'],$order['gongdeng'],$price,'JSAPI');
        }
        $paydata = $weixinpay->pay();
        if(!empty($param['price'])) {
            $paydata['order_num'] = $order['order_num'];
        }
        if(!empty($paydata['return_code'])){
            systembug('return_code为空',2,$this->url);
            return admin_json(-1, '获取失败',$paydata['return_msg']);
        }
        return admin_json(1, '获取成功',$paydata);
    }
    /**
     * [check  微信支付查询]
     * @param
     * @author [C。]
     * @return json
     */
    public function check()
    {
        $param = input('param.');
        $model = new CompanyModel;
        $rmodel = new RechargeModel;
        $cmodel = new CompanyGongdengOrderModel;
        if($param['is_act'] == 1){
            $order = $rmodel->findData($param['orderid'],'id','comid,myorderno,title');
            $order['order_num'] = $order['myorderno'];
            $order['gongdeng'] = $order['title'];
        }else{
            $order = $cmodel->findData($param['orderid'],'id','comid,order_num,gongdeng');
        }
        $data = $model->findData($order['comid'],'id','mch_id,much_secret,wx_appid,wx_secret,is_son');
        if($data['is_son'] == 2){
            $weixinpay = new \WeixinPay\WeixinPay($data['wx_appid'],$openid = '',$data['mch_id'],$data['much_secret'],$order['order_num'],$order['gongdeng'],$total_fee = '',$trade_type = '');
            $paydata = $weixinpay->check();
        }elseif($data['is_son'] == 1){
            $cmmodel = new ConfigModel;
            $appid = $cmmodel->findOne(['cname'=>'zh_appid'],'cvalue');
            $mch_id = $cmmodel->findOne(['cname'=>'zh_mch_id'],'cvalue');
            $mch_secret = $cmmodel->findOne(['cname'=>'zh_mch_secret'],'cvalue');
            $weixinpay = new \WeixinPay\WeixinServerPay($appid['cvalue'],$data['wx_appid'],'',$mch_id['cvalue'],$data['mch_id'],$mch_secret['cvalue'],$order['order_num'],$order['gongdeng'], '');
            $paydata = $weixinpay->check();
        }

        if($paydata['trade_state'] != 'SUCCESS'){
            return admin_json(-1, '没支付成功');
        }else{
            return admin_json(1, '支付成功');
        }
    }
    /**
     * [financial  获取年度财务审计]
     * @param type 1年 2月
     * @author [C。]
     * @return json
     */
    public function financial()
    {
        $param = input('param.');
        $model = new CompanyGongdengOrderModel;
        $map = [];
        $data = [];
        try{
            $map['status'] = 1;
            $map['comid'] = $param['comid'];
            if($param['type'] == 1){
                for($i = 1;$i<13;$i++){
                    if($i == 12){
                        $j = 1;
                        $year = $param['year'] + 1;
                    }else{
                        $j = $i + 1;
                        $year = $param['year'];
                    }
                    $map['create_time'] = ['between',[strtotime($param['year'].'-'.$i),strtotime($year.'-'.$j)]];
                    $data[] = $model->getSum($map,'total_price');
                }
            }elseif($param['type'] == 2){
                $days = getDaysInMonth($param['year'],$param['month']);
                for($i = 1;$i<=$days;$i++){
                    $j = $i + 1;
                    if($i == $days){
                        $j = 1;
                        $month = $param['month'] + 1;
                    }else{
                        $month = $param['month'];
                    }
                    $map['create_time'] = ['between',[strtotime($param['year'].'-'.$month.'-'.$i),strtotime($param['year'].'-'.$month.'-'.$j)]];
                    $data[] = $model->getSum($map,'total_price');
                }
            }
        }catch (\Exception $e){
            systembug($e->getMessage(),2,$this->url);
            return admin_json(-1, '获取失败' . $e->getMessage());
        }
        return admin_json(1, '获取成功',$data);
    }
    /**
     * [edit  ]
     * @param type 1点灯 3烧香
     * @author [C。]
     * @return json
     */
    public function edit()
    {
        $param = input('param.');
        $model = new CompanyGongdengOrderModel;
        $data = [];
        try{
            $data['id'] = $param['id'];
            $data['bless'] = $param['bless'];
            $data['bless_img'] = $param['bless_img'];
            $data['bless_time'] = time();
            $data['states'] = 1;
            $model->editData($data);
        }catch (\Exception $e){
            systembug($e->getMessage(),2,$this->url);
            return admin_json(-1, '修改失败' . $e->getMessage());
        }
        return admin_json(1, '成功');
    }
    /**
     * [editgongdeng  编辑供灯订单]
     * @author [C。]
     * @return json
     */
    public function editgongdeng()
    {
        $param = input('param.');
        $model = new CompanyGongdengOrderModel;
        $data = [];
        try{
            $data['id'] = $param['id'];
            $data['day'] = $param['day'];
            $data['total_price'] = $param['total_price'];
            $data['paytime'] = time();
            if(!empty($param['order_num'])){
                $data['order_num'] = $param['order_num'];
            }
            $model->editData($data);
        }catch (\Exception $e){
            systembug($e->getMessage(),2,$this->url);
            return admin_json(-1, '修改失败' . $e->getMessage());
        }
        return admin_json(1, '成功');
    }
}